﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Orchard.Localization;
using Orchard.UI.Admin;
using Szmyd.Infiltrator.Autofac;
using Szmyd.Infiltrator.ViewModels;
using System;
using Orchard;
using Orchard.Logging;
using Orchard.UI.Notify;

namespace Szmyd.Infiltrator.Controllers
{
    [Admin, ValidateInput(false)]
    public class AdminController : Controller
    {
        private readonly IOrchardServices _services;
        private readonly IProfilingManager _manager;

        public AdminController(IOrchardServices services, IProfilingManager manager) {
            _services = services;
            _manager = manager;
        }

        public Localizer T { get; set; }

        public ILogger Logger { get; set; }

        public ActionResult Index() {
            var wasStarted = _manager.IsStarted;
            if(wasStarted) _manager.Stop();
            var info = _manager.GetAll().ToList();
            var model = new ProfilingInfoViewModel
            {
                IsStarted = wasStarted,
                Info = info,
                ThreadIds = info.Select(v => v.ThreadId).Distinct()
            };
           if(wasStarted) _manager.Start();
            return View(model);
        }

        [HttpGet]
        public ActionResult Start()
        {
            try
            {
                _manager.Restart();
                _services.Notifier.Information(T("Profiling started..."));
            }
            catch (Exception ex)
            {
                Logger.Error(ex, T("Error during profiling startup").Text);
                _services.Notifier.Error(T("Error during profiling startup: {0}", ex.Message));
            }
            return this.RedirectToAction("Index", "Admin", new { area = "Szmyd.Infiltrator" });
        }

        [HttpGet]
        public ActionResult Stop()
        {
            try
            {
                _manager.Stop();
                _services.Notifier.Information(T("Profiling stopped..."));
            }
            catch (Exception ex)
            {
                Logger.Error(ex, T("Error during profiling stopping").Text);
                _services.Notifier.Error(T("Error during profiling stopping: {0}", ex.Message));
            }
            return this.RedirectToAction("Index", "Admin", new { area = "Szmyd.Infiltrator" });
        }
    }
}
